package vote.config;

import cn.dev33.satoken.stp.StpUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import vote.domain.entity.RequestInfo;


/**
 * 自定义请求拦截器，用于获取请求上下文信息并存储到ThreadLocal
 */
@Component
public class RequestContextInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String ip = getClientIp(request);
        // 这里Sa-Token已完成token校验，直接获取登录ID作为OpenId
        String openId = StpUtil.getLoginIdAsString();
        RequestInfo requestInfo = new RequestInfo();
        requestInfo.setOpenId(openId);
        requestInfo.setIp(ip);
        RequestHolder.set(requestInfo);
        return true; // 继续执行后续流程
    }
    /**
     * 获取客户端真实IP（处理代理服务器情况）
     */
    private String getClientIp(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        // 处理多个IP情况（如多级代理），取第一个有效IP
        return ip.split(",")[0].trim();
    }
}


